package com.project.fiveCerealsSavoury.aop;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.project.fiveCerealsSavoury.domain.User;


@Aspect
public class AOP {
	@Before(value="pointcut()")
	public void before() throws ServletException, IOException{
 	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	request.setCharacterEncoding("UTF-8");
	HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		List<String> suffixs = Arrays.asList("addWage","outs","setAdmin","addLogistics","upload","amend","delete","list","queryCompany","con","dispose","ckgl","queryFinance","queryList","admin","queryOrder","delete","addDelivery");
		List<String> suffix =Arrays.asList("reg","login","que.do","adminReg","adminLogin","/good/single","queryGoodName.do");
		String requestURI = request.getRequestURI();
		String parameter = request.getParameter("isQuery");
		HttpSession session = request.getSession();
		for (String strings : suffix) {
			if (requestURI.contains(strings)) {
				return;
			}
		}
		for (String string : suffixs) {
			if (requestURI.contains(string)) {
				String name = (String) session.getAttribute("name");
				if (name != null) {
					request.setAttribute("name", name);
					return;
				}else{
					if (requestURI.contains("/queryList.do") && parameter == null) {
						break;
					}
					request.getRequestDispatcher("/adminLogin.htm").forward(request, response);;
					return;
				}
			}
		}
		User user = (User) session.getAttribute("USER");
		if (user != null){
			request.setAttribute("name", user.getName());
			return;
		}else{
			request.getRequestDispatcher("/login.htm").forward(request, response);
		}
		
	}
	
	@After(value="pointcut()")
	public void after() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("USER");
		if (user != null) {
			request.setAttribute("name", user.getName());
		}
		response.setCharacterEncoding("UTF-8");
	}
	
	@Pointcut("execution(* com.project.fiveCerealsSavoury.controller.*.*(..))")
	public void pointcut(){}
}
